package com.zyf.heixiang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zyf.heixiang.common.BaseContext;
import com.zyf.heixiang.common.CustomException;
import com.zyf.heixiang.common.R;
import com.zyf.heixiang.entity.ShoppingCart;
import com.zyf.heixiang.service.DishFlavorService;
import com.zyf.heixiang.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author DL5O
 * @version 1.0
 */
@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * add添加购物车数据到数据库
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        log.info("购物车数据{}", shoppingCart.toString());
        //1.设置用户id，指定当前是哪个用户的购物车数据
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);

        //2.查询当前菜品或者套餐是否在购物车中，编写sql
        //3.sql:select * from shopping_cart where user_id = ? and dish_id/setmeal_id = ?
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, userId);
        qw.eq(shoppingCart.getDishId() != null,
                ShoppingCart::getDishId, shoppingCart.getDishId());
        qw.eq(shoppingCart.getSetmealId() != null,
                ShoppingCart::getSetmealId, shoppingCart.getSetmealId());

        //4.根据条件去查询
        ShoppingCart cartServiceOne = shoppingCartService.getOne(qw);
        if (cartServiceOne != null) {
            //如果已经存在，且口味一致就在原来数量基础上+1
            //进行数量的修改
            Integer number = cartServiceOne.getNumber();//原先的数量
            cartServiceOne.setNumber(number + 1);
            shoppingCartService.updateById(cartServiceOne);
        } else {
            //如果不存在，或者口味不一致添加到购物车，数量默认就是1
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
        }

        return cartServiceOne != null ? R.success(cartServiceOne) : R.success(shoppingCart);
    }

    /**
     * 获取购物车数据,查看购物车
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list() {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, userId);
        qw.orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> list = shoppingCartService.list(qw);
        return list != null ? R.success(list) : R.error("获取购物车信息失败");
    }

    /**
     * 根据用户id 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> clean() {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, userId);
        boolean flag = shoppingCartService.remove(qw);
        return flag ? R.success("删除成功") : R.error("删除失败");
    }

    /**
     * 修改id
     * @param shoppingCart
     * @return
     */
    @PostMapping("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart) {
        //1.获取用户id
        Long userId = BaseContext.getCurrentId();

        //2.根据dish_id 或者 setmeal_id,以及用户id 查询对应的菜品信息
        //sql: select * from shopping_cart where dish_id/setmeal_id = ? and userId=?
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId());
        qw.eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        qw.eq(ShoppingCart::getUserId, userId);

        //3.进行查询
        ShoppingCart info = shoppingCartService.getOne(qw);
        //4.如果info为null，或者info.getNumber==0,抛出异常
        if (info == null || info.getNumber() <= 0) throw new CustomException("该菜品记录不存在！");

        //5.进行菜品数量的--
        Integer number = info.getNumber();
        info.setNumber(--number);

        //6.如果菜品数量为0，就移除该条购物车信息
        log.info("number={}", number);
        if (number == 0) {
            shoppingCartService.removeById(info);
        }
        //7.进行数量的修改并保存
        shoppingCartService.updateById(info);

        return R.success(info);
    }
}
